<?php
namespace My\Controller;

use Utuo\BackgroundController;

class MallController extends BackgroundController {

	public function _initialize() {
		$this->setControllerTitle('分销商城信息设置');
		$this->setActionTitle(array(
				'index' => '分销商城信息',
				'config' => '分销商城配置',
				'wechat' => '分销微信回复设置',
				'url' => '分销商城地址',
				'certUrl' => '证书查询地址',
		));
		$this->setActionNav('index,config,wechat,url,certUrl');
	}
	
	// 商城信息
	public function indexAction() {
		$dProduct = D('Mall');
		$mall = $dProduct->find($this->aid);
		if ( !$mall ) {
			$data = array(
					'id' => $this->aid,
					'cid' => $this->aid,
					'name' => $this->aname
			);
			if (!$dProduct->add($data)) {
				$this->error('添加商城信息失败');
			}
			$mall = $dProduct->find($this->aid);
		}
		$mall['status'] = $this->getRadio('status', $dProduct->status, $mall['status']);
		$this->assign('mall', $mall);
		$this->display('save');
	}
	
	// 首页地址
	public function urlAction() {
		$mall = M('Mall')->find($this->aid);
		$mall['url'] = url('Home', 'Mall', 'index', "sid={$this->aid}", true);
		$this->assign('mall', $mall);
		$this->display();
	}
	
	// 证书查询地址
	public function certUrlAction() {
		$mall = array();
		$mall['url'] = url('Home', 'MallCert', 'search', "sid={$this->aid}", true);
		$this->assign('mall', $mall);
		$this->display();
	}
	
	// 微信回复设置
	public function wechatAction() {
		$wechat_rule = '__mall_rule__';
		$d = D('WechatReply');
		$reply = $d->getReply($this->aid, $wechat_rule);
		if (!$reply) {
			$url = url('Home', 'Mall', 'index', 'sid=' . $this->aid, true);
			$id = $d->setKeywordReply($this->aid, $wechat_rule, '微分销', '微分销', '点击进入【微分销】', '', $url);
			$id && $reply = $d->find($id);
		}
		$reply['keyword'] = trim($reply['keyword'], ' ,');
		$this->assign('reply', $reply);
		$this->display();
	}
	
	// 提交微信回复
	public function wechatPostAction() {
		$d = D('WechatReply');
		if ($d->create()) {
			$d->keyword = $d->parseKeyword($d->keyword);
			if ($d->save()) {
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError();
	}
	
	/**
	 * 分销商城基础配置
	 * @see \Utuo\BackgroundController::saveAction()
	 */
	public function saveAction() {
		parent::saveAction();
	}
	
	/**
	 * 商城扩展配置
	 */
	public function configAction() {
		$dMallConfig = D('MallConfig');
		$mall = $dMallConfig->find($this->aid);
		if ( !$mall ) {
			$data = array(
					'id' => $this->aid,
					'cid' => $this->aid,
					'name' => $this->aname
			);
			if (!$dMallConfig->add($data)) {
				$this->error('添加商城扩展信息失败');
			}
			$mall = $dMallConfig->find($this->aid);
		}
		$this->assign('mallConfig', $mall);
		$this->display('config');
	}
	
	/**
	 * 商城扩展配置
	 */
	public function saveConfigAction() {
		parent::submitPost('MallConfig');
	}
	
}